﻿using System;
using System.Net;

namespace Up2Link.Util
{
    /// <summary>
    /// 用于获取本地主机ip地址的类
    /// </summary>
    public class CIPProbe
    {
        /// <summary>
        /// 本地主机的ip地址数组
        /// </summary>
        private IPAddress[] adrs;

        /// <summary>
        /// 将本地主机的所有ip地址转化为字符串后组成的数组
        /// </summary>
        private String[] adrStrs;

        /// <summary>
        /// 本地主机ip地址的数量
        /// </summary>
        private Int32 adrCount;

        /// <summary>
        /// 无参数构造函数
        /// </summary>
        public CIPProbe()
        {
            try
            {
                //获取本地主机ip地址数组
                adrs = Dns.GetHostAddresses(Dns.GetHostName());
                
                //获取本地主机ip地址数量信息
                adrCount = adrs.Length;

                //创建字符串数组
                adrStrs = new String[adrCount];

                //将每一个ip地址转化为字符串后存储到字符串数组中
                for (Int32 i = 0; i < adrCount; i++)
                {
                    adrStrs[i] = adrs[i].ToString();
                }
            }
            catch (Exception e)
            {
                //如果构造函数执行过程中捕捉到异常，则将所有成员置为默认值
                adrCount = 0;
                adrs = null;
                adrStrs = null;

                //System.Console.WriteLine(e.StackTrace);
            }
        }

        //只读属性，分别返回三个成员变量
        /// <summary>
        /// 返回地址数组
        /// </summary>
        public IPAddress[] Addresses
        {
            get { return adrs; }
        }

        /// <summary>
        /// 返回地址字符串数组
        /// </summary>
        public String[] AdrStrings
        {
            get { return adrStrs; }
        }

        /// <summary>
        /// 返回地址数量
        /// </summary>
        public Int32 AddressCount
        {
            get { return adrCount; }
        }
    }
}
